import {getRealUrl} from './httpRequet'
function post(config){
    let url=getRealUrl(config.url,true,config.urlparam);
    let $XMLHttpRequest=window._XMLHttpRequest||window.XMLHttpRequest
    const xhr = new $XMLHttpRequest()
    let timeout=config.timeout||5000;
    let paramStr = ''
    for(let key in config.params){
        paramStr += key+'='+config.params[key]+'&'
        // formData.append(key,config.params[key])
    }
    paramStr = paramStr.substring(0,paramStr.length-1);
    let timeoutobj=null;
    function setTime(){
        if(timeout==-1)return;
        timeoutobj=setTimeout(function(){
            xhr.abort();
            xhr.onerror();
        },timeout)
    }
    xhr.withCredentials=true
    xhr.onreadystatechange = (e) => {
        if(timeoutobj!=null)
        clearTimeout(timeoutobj);
        if (xhr.readyState ==3){
            //持续输出中
            if(xhr.response.length>2000){
                let allmsg=xhr.response.substr(2000);
               // console.log(allmsg);
                if(xhr.curmsg==undefined)xhr.curmsg=allmsg;
                else{
                    xhr.curmsg=allmsg.substr(xhr.received.length);
                }
                xhr.received=allmsg;
                if(config.onMessage)
                config.onMessage(xhr,xhr.curmsg,'3')
            }
            setTime();
        }
        if(xhr.readyState==4){
            //结束
            config.onMessage(xhr,xhr.curmsg||xhr.responseText.substr(2000),'4')
        }
    }
    
    xhr.open('POST', url)
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
    xhr.setRequestHeader("Accept","application/json, text/plain, */*")
    xhr.onerror=()=>config.onError||{}
    setTime();
    xhr.send(paramStr)
    
}
//import {postrequest} from ""
//postrequest({params:{},url:"",urlparam:"",onMessage:(xhr,responsetext,3|4)=>{}})
export const postrequest=post;
